package com.zhaoyu.wemedia.filter;

import com.zhaoyu.utils.threadlocal.WmThreadLocalUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 创建过滤器,拦截所有请求,把用户id放入WmThreadLocalUtils
 */
@WebFilter(urlPatterns = "/*",filterName = "UserIdFilter")
public class UserIdFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 获取网关转发过来的请求对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // 从请求对象的头中获取userID
        String userId = request.getHeader("userId");
        if(userId != null){ // 如果userId不为空,把userId放入WmThreadLocalUtils
            int uid = Integer.parseInt(userId); // 将userId转换为int类型
            WmThreadLocalUtils.setUserId(uid); // 将userId放入WmThreadLocalUtils
        }
        filterChain.doFilter(request,servletResponse); // 进行下一个过滤器
    }

}